//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Resource Application Block
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Common.Instrumentation.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.ObjectBuilder;

namespace EntLibContrib.Resource.Instrumentation
{
	/// <summary>
	/// This type supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
	/// Represents the process to build a <see cref="ResourceInstrumentationListener"/> according to the instrumentation configuration.
	/// </summary>
	public class ResourceInstrumentationListenerCustomFactory : ICustomFactory
	{
		#region Public Methods
		/// <summary>
		/// This method supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
		/// Builds a <see cref="ResourceInstrumentationListener"/>.
		/// </summary>
		/// <param name="context">The <see cref="IBuilderContext"/> that represents the current building process.</param>
		/// <param name="name">The name of the instance to build.</param>
		/// <param name="configurationSource">The source for configuration objects.</param>
		/// <param name="reflectionCache">The cache to use retrieving reflection information.</param>
		/// <returns>A fully initialized instance of <see cref="ResourceInstrumentationListener"/>.</returns>
		public object CreateObject(IBuilderContext context, string name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
		{
			InstrumentationConfigurationSection objectConfiguration = GetConfiguration(configurationSource);

			ResourceInstrumentationListener createdObject = new ResourceInstrumentationListener(name, objectConfiguration.PerformanceCountersEnabled, objectConfiguration.EventLoggingEnabled, objectConfiguration.WmiEnabled);

			return createdObject;
		}
		#endregion

		#region Private Methods
		private InstrumentationConfigurationSection GetConfiguration(IConfigurationSource configurationSource)
		{
			InstrumentationConfigurationSection configurationSection = (InstrumentationConfigurationSection)configurationSource.GetSection(InstrumentationConfigurationSection.SectionName);
			if (configurationSection == null) 
				configurationSection = new InstrumentationConfigurationSection(false, false, false);

			return configurationSection;
		}
		#endregion
	}
}